
import {Pixi} from '@/pixi/index'
import './pixi.scss'
import {onBeforeUnmount, onDeactivated, ref, toRaw} from "vue";

import {callBacks, isEmptyObj, isArray} from '@/utils/index'

let allDashs = ref([]);
function stopLine(){
    // console.log('停止stopLine')
    allDashs.value.forEach((item,index)=>{
        item.stopLoop()
    })
}

let allPaths = ref([]);
function stopPath(){
    // console.log('停止Path')
    allPaths.value.forEach((item,index)=>{
        item.stopLoop()
    })
}

let pixiRef = ref(null)

export let useByJson = async (params) => {
    // 如果路由用了key 自动刷新 所以不用before销毁了
    onBeforeUnmount(()=>{
        console.log('onBeforeUnmount')
        pixi.destory(()=>callBacks(stopLine,stopPath))
    })
    // keepalve
    onDeactivated(()=>{
        console.log('onDeactivated')
        pixi.destory(()=>callBacks(stopLine,stopPath))
    })

    let {
        app = {},
        bgParams = {},
        textOptions = [],
        imgSpriteArr = [],
        dashArr = [],
        pathArr =[],
        domSprites = [],
        mouseParams = {},
    } = params

    if(!app){
        return
    }


    // 初始化 pixi
    pixiRef.value = await Pixi.create(app)

    let pixi = pixiRef.value

    // 创建背景
    if(!isEmptyObj(bgParams)){
        pixi.createBg(bgParams)
    }
    // 显示hello world文字
    if(isArray(textOptions) && textOptions.length){
        textOptions.forEach(item=>{
            pixi.createText(item)
        })
    }

    // 创建图片精灵
    if(isArray(imgSpriteArr) && imgSpriteArr.length){
        imgSpriteArr.forEach(item=>{
            pixi.createSprite(item)
        })
    }

    // 绘制 虚线
    if(isArray(dashArr) && dashArr.length){
        dashArr.forEach((item)=>{
            allDashs.value.push(pixi.createDash(item))
        })
    }

    //创建轨迹线
    if(isArray(pathArr) && pathArr.length){
        pathArr.forEach((item)=>{
            item.linewidth = toRaw(Pixi.textures[item.line]).orig.height;
            item.bgUrl = Pixi.textures[item.line]
            allPaths.value.push( pixi.createPath(item))
        })
    }

    // 绘制dom精灵
    if(isArray(domSprites) && domSprites.length){
        for(let i=0; i<domSprites.length;i++){
            await pixi.createDomSprite(domSprites[i])
        }
    }

    // container容器增加 childs
    pixi.containerAddChilds()
    // 添加鼠标控件 showCoord:true // 开启点击显示坐标。 默认不开启false
    pixi.addMouseControles(mouseParams)
    // 添加resize控件
    // pixi.addResizeControles()

    // 测试
    // setTimeout(()=>{
    //   pixi.destory(()=>callBacks(stopLine,stopPath,testConsole))
    // },3000)

    // 通过返回值暴露所管理的状态
    return { pixiRef,allDashs,allPaths}
}
